"""
Tools API routes for web search and weather query
工具API路由 - 联网搜索和天气查询
"""

from fastapi import APIRouter, Form, HTTPException, Depends
from sqlalchemy.orm import Session
from db.connection import get_db
from services.tools import tools_service
from typing import Dict, Any
import asyncio
import time

router = APIRouter(prefix="/api/tools", tags=["tools"])


@router.post("/search")
async def web_search(
    query: str = Form(..., description="搜索查询词"),
    max_results: int = Form(5, description="最大返回结果数量"),
    db: Session = Depends(get_db)
) -> Dict[str, Any]:
    """
    联网搜索API
    
    Args:
        query: 搜索查询词
        max_results: 最大返回结果数量
        
    Returns:
        包含搜索结果的字典
    """
    try:
        result = await tools_service.web_search(query, max_results)
        return result
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"搜索失败: {str(e)}")


@router.post("/weather")
async def get_weather(
    location: str = Form(..., description="地点名称"),
    db: Session = Depends(get_db)
) -> Dict[str, Any]:
    """
    天气查询API
    
    Args:
        location: 地点名称
        
    Returns:
        包含天气信息的字典
    """
    try:
        result = await tools_service.get_weather(location)
        return result
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"天气查询失败: {str(e)}")


@router.post("/analyze-need")
async def analyze_tool_need(
    user_message: str = Form(..., description="用户消息"),
    db: Session = Depends(get_db)
) -> Dict[str, Any]:
    """
    分析用户消息是否需要调用工具
    
    Args:
        user_message: 用户消息
        
    Returns:
        包含工具需求分析的字典
    """
    try:
        result = await tools_service.analyze_tool_need(user_message)
        return result
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"工具需求分析失败: {str(e)}")


@router.get("/health")
async def health_check() -> Dict[str, Any]:
    """
    工具服务健康检查
    
    Returns:
        健康状态
    """
    try:
        # 测试工具服务是否正常工作
        test_analysis = await tools_service.analyze_tool_need("测试消息")
        
        return {
            "status": "healthy",
            "tools_service": "available",
            "test_analysis": test_analysis,
            "timestamp": asyncio.get_event_loop().time()
        }
    except Exception as e:
        return {
            "status": "unhealthy",
            "error": str(e),
            "timestamp": asyncio.get_event_loop().time()
        }


@router.get("/websocket-status")
async def get_websocket_status(db: Session = Depends(get_db)) -> Dict[str, Any]:
    """
    获取WebSocket服务器状态
    
    Returns:
        WebSocket服务器状态
    """
    try:
        # 这里需要访问WebSocket服务器的状态
        # 由于WebSocket服务器是独立运行的，我们只能返回基本信息
        return {
            "status": "running",
            "message": "WebSocket服务器状态需要从服务器日志中查看",
            "suggestions": [
                "检查WebSocket服务器日志",
                "确认端侧连接状态",
                "验证响应格式是否正确"
            ],
            "timestamp": time.time()
        }
    except Exception as e:
        return {
            "status": "error",
            "error": str(e),
            "timestamp": time.time()
        }
